
export default class EventBridge
{
    static getMessageHandler(name) {
        if (window && window.webkit && window.webkit.messageHandlers) {
            return window.webkit.messageHandlers[name];
        }
        return undefined;
    }

    static getWebViewID() {
        if (typeof __MY_ID__ !== "undefined") {
            return __MY_ID__;
        }
        return "(null)";
    }

    static postMessage(name, params)
    {
        let publish = EventBridge.getMessageHandler('publish');
        if (publish) {
            params = params || {};
            params['name'] = name;
            params['from'] = EventBridge.getWebViewID();
            console.log('webview: postMessage: ' + JSON.stringify(params));

            publish.postMessage(params);
        }
        else {
            console.log('webview: publish not found');
        }
    }

    static log(text) {
        if (typeof text !== 'string') {
            text = text.toString();
        }
        let invoke = EventBridge.getMessageHandler('invoke');
        if (invoke) {
            invoke.postMessage({ name: "log", log: text, from: EventBridge.getWebViewID()});
            return true;
        }
        return false;
    }

    static subscribe(name, callback, broadcast=true) {
        if (broadcast === undefined) {
            broadcast = true;
        }
        
        let subscribe = EventBridge.getMessageHandler('subscribe');
        if (subscribe) {
            let param = {
               name: (broadcast ? name : (name + "-" + EventBridge.getWebViewID())),
               from: EventBridge.getWebViewID(),
               callback: callback
            };
            subscribe.postMessage(param);
            console.log('webview: subscribe: ' + JSON.stringify(param));
        }
        else {
            console.log('webview: subscribe not found');
        }
    }
}

export {EventBridge};
